<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/10/22
 * Time: 10:53
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\admin\middleware;

use app\common\business\User;
use app\common\lib\Show;
use think\Exception;
use think\facade\Cookie;
use think\facade\Log;
use think\facade\Session;

class Auth
{
    /**
     * 处理中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Redirect
     */
    public function handle($request, \Closure $next)
    {
        Log::header(Show::json_encode($request->header()));

        if (!preg_match('/login/', strtolower($request->pathinfo()))) {
            $getSession = Session::get(config('admin.admin_session_key'));
            $getCookie = Cookie::get(config('admin.admin_session_key'));
            if(!$getSession && !$getCookie){
                return redirect((string)url('login/index', ['url' => base64_encode(request()->url())], false, false));
            }
            $userSession = "";
            if(!empty($getSession)){
                $userSession = $getSession;
            }
            if(!empty($getCookie)){
                $userSession = $getCookie;
            }
            list($key1,$userId,$key2) = explode('-',$userSession);

            if($userId != 1){
                //查询权限
                try {
                    $user = (new User())->getBaseById((int)$userId);
                }catch (\Exception $e){
                    throw new Exception("查询失败");
                }
                if(!$user || $user['status'] != 1){
                    throw new \Exception("用户不存在");
                }

                $request->userRuleId = $user['rule_id'];
            }
            $request->userId = $userId;
        }

        return $next($request);
    }
}
